<template>
  <div class="filterWrapper">
    <div
      class="filterGroup"
      v-for="(filter, groupIndex) in filterOptions"
      :key="groupIndex"
    >
      <p class="filterTitle">{{ filter.name }}</p>
      <div class="filterOptions">
        <a
          v-for="option in filter.childs"
          :key="option.id"
          href="javascript:void(0)"
          :class="{ active: selectedIds[groupIndex] === option.id }"
          @click="selectOption(option.id, groupIndex)"
        >
          {{ option.name }}
        </a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';

// 接收父组件传递的 `filterOptions` 和 `defaultSelected` 配置
const props = defineProps({
  filterOptions: {
    type: Array,
    required: true, // 父组件传入筛选数据，必填
  },
  defaultSelected: {
    type: Array,
    default: () => [], // 每组默认选中的 `id`
  },
  selectedId: {
    type: Array,
    default: () => [],
  },
});

// 向父组件传递选中的 ID
const emit = defineEmits(['updateSelected']);

// 保存每组的选中状态
const selectedIds = ref([]);

// 初始化选中状态，并动态插入 "不限" 项
onMounted(() => {
  props.filterOptions.forEach((filter, index) => {
    // 检查当前组是否已经有 "不限" 选项
    const hasNoLimitOption = filter.childs.some((option) => option.id === 0);

    if (!hasNoLimitOption) {
      // 动态插入 "不限" 项，id 为 0
      filter.childs.unshift({ id: 0, name: '不限' });
    }

    // 默认选中 "不限"（id: 0）或父组件传入的默认选项
    selectedIds.value[index] = props.defaultSelected[index] ?? 0;
  });
});

// 点击选项时更新选中状态并通知父组件
const selectOption = (id, groupIndex) => {
  selectedIds.value[groupIndex] = id; // 更新当前分类的选中状态
  emit('updateSelected', { selectedIds: [...selectedIds.value] }); // 通知父组件所有分类的选中状态
};

// 监听父组件传递的 selectedId 的变化
watch(
  () => props.selectedId,
  (newSelectedId) => {
    if (Object.keys(newSelectedId).length) {
      // 根据父组件传递的数据更新状态
      Object.keys(newSelectedId).forEach((groupIndex) => {
        selectedIds.value[groupIndex] = newSelectedId[groupIndex];
      });
    }
  },
  { deep: true, immediate: true }, // 深度监听并立即执行
);
</script>

<style scoped>
.filterWrapper {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filterGroup {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filterTitle {
  font-size: 14px;
  font-weight: bold;
  margin-right: 10px;
  color: #888;
}

.filterOptions a {
  margin-right: 10px;
  color: #333;
  text-decoration: none;
  cursor: pointer;
}

.filterOptions a.active {
  color: red;
  font-weight: bold;
  border: 1px solid red;
  padding: 2px 5px;
  border-radius: 3px;
}
</style>
